package com.abner.basis.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 实现线程定制化通信
 *  有3个线程分别为A、B、C, A打印2此 -> B打印3次 -> C打印4次 执行3次共
 * @Author yuhui
 * @Date: 2024/3/20
 */
public class ThreadCustomComm {
    public static void main(String[] args) {
        Share share = new Share();

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    share.print2();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"A").start();

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    share.print3();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"B").start();

        new Thread(() -> {
            for (int i = 0; i < 3; i++) {
                try {
                    share.print4();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        },"C").start();
    }

}

class Share {

    /**
     * 标识
     *  1: A线程进行执行
     *  2: B线程进行执行
     *  3: C线程进行执行
     */
    private int flag = 1;

    private Lock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();
    private Condition conditionC = lock.newCondition();

    /**
     * 打印2次
     */
    public void print2() throws InterruptedException {
        lock.lock();
        try {
            while (flag != 1) {
                conditionA.await();
            }
            for (int i = 0; i < 2; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了: "+i+"次");
            }
            flag = 2;
            conditionB.signal();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 打印3次
     */
    public void print3() throws InterruptedException{
        lock.lock();
        try {
            while (flag != 2) {
                conditionB.await();
            }
            for (int i = 0; i < 3; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了: "+ (i+1) +"次");
            }
            flag = 3;
            conditionC.signal();
        }finally {
            lock.unlock();
        }
    }

    /**
     * 打印4次
     */
    public void print4() throws InterruptedException{
        lock.lock();
        try {
            while (flag != 3) {
                conditionC.await();
            }
            for (int i = 0; i < 4; i++) {
                System.out.println(Thread.currentThread().getName()+"打印了: "+i+"次");
            }
            flag = 1;
            conditionA.signal();
        }finally {
            lock.unlock();
        }
    }
}